<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Organization\Service;

use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use Plugin\Organization\Repository\RdOrganizeAreaRepository;
use Plugin\Organization\Repository\RdOrganizeAreaStandRepository;
use App\Service\IService;

/**
 * 站点表服务类
 */
final class RdOrganizeAreaStandService extends IService
{
    public function __construct(
        protected readonly RdOrganizeAreaStandRepository $repository,
        protected readonly RdOrganizeAreaRepository $areaRepository,
    ) {}

    public function getAllowedUpdateData($data): array
    {
        return array_flip(['area_id', 'name', 'abbr', 'addr', 'longitude', 'latitude', 'status', 'sort', 'remark']);
    }

    public function create(array $data): mixed
    {
        $areaId = $data['area_id'];
        $area = $this->areaRepository->findById($areaId);
        if (!$area) {
            throw new BusinessException(ResultCode::NOT_FOUND, '项目不存在');
        }
        return parent::create(array_merge($data, [
            'zone_id' => $area->zone_id,
            'proj_line_id' => $area->proj_line_id
        ]));
    }

    /**
     * 根据工区ID删除站点
     * @param mixed $id 工区ID或ID数组
     */
    public function deleteByAreaId(mixed $id): int
    {
        if (is_int($id)) {
            $id = [$id];
        }
        // 直接删除关联的站点
        return $this->repository->getQuery()->whereIn('area_id', $id)->delete();
    }
}